"use client";

// 引入 React 相关的 hooks
import type React from "react";
import { useState, useRef, useEffect } from "react";
// 引入 pdfjs-dist 库，用于处理 PDF 文件
import * as pdfjsLib from "pdfjs-dist";
// 引入 pdfjs-dist 的 CSS 文件
import "pdfjs-dist/web/pdf_viewer.css";
// 引入自定义的 CSS 文件
import "./PdfViewer.css";
import "./index.css";

// 设置 pdfjsLib 的全局 worker 源
pdfjsLib.GlobalWorkerOptions.workerSrc = `./pdf.worker.mjs`;

// 定义标注类型
interface Annotation {
  id: string;
  text: string;
  color: string;
  pageNumber: number;
  position: {
    top: number;
    left: number;
    width: number;
    height: number;
  };
  note?: string;
}

const PdfTest: React.FC = () => {
  const [message, setMessage] = useState(""); // 用于存储 PDF 文件 || 发送消息的信息
  const pdfContainerRef = useRef<HTMLDivElement>(null); // 用于存储 PDF 容器的 ref
  const [annotations, setAnnotations] = useState<Annotation[]>([]); // 存储所有标注
  const [showAnnotationPopup, setShowAnnotationPopup] = useState(false); // 控制标注弹窗显示
  const [currentSelection, setCurrentSelection] = useState<{
    text: string;
    range?: Range;
    pageNumber?: number;
  }>({ text: "" }); // 当前选中的文本信息
  const [annotationNote, setAnnotationNote] = useState(""); // 标注备注
  const [annotationColor, setAnnotationColor] = useState("#FFEB3B"); // 默认标注颜色
  const popupRef = useRef<HTMLDivElement>(null); // 标注弹窗的ref

  const handleSendMessage = () => {}; // 处理发送消息的函数
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {};

  const handlePdfUpload = (file: File) => {
    setMessage(file.name);
    const fileReader = new FileReader(); // 创建一个 FileReader 对象
    fileReader.onload = () => {
      const typedArray = new Uint8Array(fileReader.result as ArrayBuffer); // 将 FileReader 的结果转换为 Uint8Array
      renderPDF(typedArray); // 调用 renderPDF 函数，传入 Uint8Array
    };
    fileReader.readAsArrayBuffer(file);
  }; // 处理 PDF 文件上传

  const renderPDF = async (typedArray: Uint8Array) => {
    if (!pdfContainerRef.current) return; // 如果 pdfContainerRef.current 为 null，则返回
    pdfContainerRef.current.innerHTML = ""; // 清空 pdfContainerRef.current 的内容
    const pdf = await pdfjsLib.getDocument({ data: typedArray }).promise; // 创建一个 PDF 文档加载任务
    for (let i = 1; i <= pdf.numPages; i++) {
      const page = await pdf.getPage(i); // 获取 PDF 文档的第 i 页
      const scale = 1.56; // 设置缩放比例
      const viewport = page.getViewport({ scale }); // 获取页面的视口

      // 创建页面容器
      const pageDiv = document.createElement("div");
      pageDiv.setAttribute("data-page-number", i.toString());
      pageDiv.style.position = "relative";
      pageDiv.style.width = `${viewport.width}px`;
      pageDiv.style.height = `${viewport.height}px`;
      pageDiv.style.margin = "0 auto 20px";
      pageDiv.style.border = "1px solid #ccc";

      // 创建Canvas用于渲染PDF背景
      const canvas = document.createElement("canvas");
      const context = canvas.getContext("2d");
      // 检查Canvas上下文是否存在
      if (!context) return;
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      canvas.style.position = "absolute";
      pageDiv.appendChild(canvas);

      // 创建文本层容器
      const textLayerDiv = document.createElement("div");
      textLayerDiv.className = "textLayer";
      textLayerDiv.style.position = "absolute";
      textLayerDiv.style.inset = "0";
      pageDiv.appendChild(textLayerDiv);

      // 创建标注层
      const annotationLayerDiv = document.createElement("div");
      annotationLayerDiv.className = "annotationLayer";
      annotationLayerDiv.style.position = "absolute";
      annotationLayerDiv.style.inset = "0";
      annotationLayerDiv.style.pointerEvents = "none";
      pageDiv.appendChild(annotationLayerDiv);

      // 渲染PDF页面到Canvas
      const renderContext = {
        canvasContext: context,
        viewport: viewport,
      };
      await page.render(renderContext).promise;

      // 提取并渲染文本层
      const textContent = await page.getTextContent(); // 获取当前页面文本内容
      const textLayer = new pdfjsLib.TextLayer({
        textContentSource: textContent,
        container: textLayerDiv,
        viewport: viewport,
      });
      await textLayer.render();

      // 将页面容器添加到PDF查看器中
      pdfContainerRef.current?.appendChild(pageDiv);
    }

    // 渲染已有的标注
    renderAnnotations();
  };

  // 渲染所有标注
  const renderAnnotations = () => {
    // 清除所有现有标注和文本标签
    document
      .querySelectorAll(".annotation-highlight, .annotation-text")
      .forEach((el) => el.remove());

    // 重新渲染所有标注
    annotations.forEach((annotation) => {
      const pageElement = document.querySelector(
        `[data-page-number="${annotation.pageNumber}"] .annotationLayer`
      );
      if (pageElement) {
        const highlightElement = document.createElement("div");
        highlightElement.className = "annotation-highlight";
        highlightElement.style.position = "absolute";
        // 使用背景色而不是下划线
        highlightElement.style.backgroundColor = annotation.color;
        highlightElement.style.opacity = "0.3";
        highlightElement.style.top = `${annotation.position.top}px`;
        highlightElement.style.left = `${annotation.position.left}px`;
        highlightElement.style.width = `${annotation.position.width}px`;
        highlightElement.style.height = `${annotation.position.height}px`;
        highlightElement.setAttribute("data-annotation-id", annotation.id);
        highlightElement.title = annotation.note || annotation.text;

        pageElement.appendChild(highlightElement);
      }
    });
  };

  // 处理文本选择
  const handleTextSelection = () => {
    const selection = window.getSelection();
    if (!selection || selection.isCollapsed) {
      // 如果没有选中文本，隐藏弹窗
      setShowAnnotationPopup(false);
      return;
    }

    const selectedText = selection.toString().trim();
    if (!selectedText) {
      setShowAnnotationPopup(false);
      return;
    }

    // 获取选中文本的范围
    const range = selection.getRangeAt(0);

    // 获取选中文本所在的页码
    const textLayerElement = range.commonAncestorContainer.parentElement;
    const pageElement = textLayerElement?.closest("[data-page-number]");
    const pageNumber = pageElement
      ? Number.parseInt(pageElement.getAttribute("data-page-number") || "1")
      : 1;

    // 保存当前选中的文本信息
    setCurrentSelection({
      text: selectedText,
      range: range,
      pageNumber: pageNumber,
    });

    // 显示标注弹窗
    setShowAnnotationPopup(true);
    setAnnotationNote(""); // 清空之前的备注

    // 定位弹窗位置
    if (popupRef.current) {
      const rect = range.getBoundingClientRect();
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const scrollLeft = window.scrollX || document.documentElement.scrollLeft;

      popupRef.current.style.top = `${rect.bottom + scrollTop + 10}px`;
      popupRef.current.style.left = `${rect.left + scrollLeft}px`;
    }
  };

  // 创建标注
  const createAnnotation = () => {
    if (
      !currentSelection.text ||
      !currentSelection.range ||
      !currentSelection.pageNumber
    ) {
      return;
    }

    const range = currentSelection.range;
    const rect = range.getBoundingClientRect();

    // 获取相对于页面的位置
    const pageElement = document.querySelector(
      `[data-page-number="${currentSelection.pageNumber}"]`
    );
    if (!pageElement) return;

    const pageRect = pageElement.getBoundingClientRect();
    const position = {
      top: rect.top - pageRect.top,
      left: rect.left - pageRect.left,
      width: rect.width,
      height: rect.height,
    };

    // 创建新标注
    const newAnnotation: Annotation = {
      id: Date.now().toString(),
      text: currentSelection.text,
      color: annotationColor,
      pageNumber: currentSelection.pageNumber,
      position: position,
      note: annotationNote,
    };

    // 添加到标注列表并立即更新状态
    const updatedAnnotations = [...annotations, newAnnotation];
    setAnnotations(updatedAnnotations);

    // 立即渲染新标注，不使用setTimeout
    renderAnnotations();

    // 隐藏弹窗
    setShowAnnotationPopup(false);

    // 清除选择
    window.getSelection()?.removeAllRanges();
  };

  // 取消标注
  const cancelAnnotation = () => {
    setShowAnnotationPopup(false);
    window.getSelection()?.removeAllRanges();
  };

  // 删除标注
  const deleteAnnotation = (id: string) => {
    const updatedAnnotations = annotations.filter((anno) => anno.id !== id);
    setAnnotations(updatedAnnotations);

    // 立即渲染更新后的标注，不使用setTimeout
    renderAnnotations();
  };

  // 当标注列表变化时重新渲染
  useEffect(() => {
    if (pdfContainerRef.current) {
      renderAnnotations();
    }
  }, [annotations]);

  return (
    <div className="w-full h-screen flex flex-col">
      <div className="upload relative">
        <input
          type="input"
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        />
        <input
          type="file"
          id="pdf-upload"
          accept="application/pdf"
          style={{ display: "none" }}
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) handlePdfUpload(file);
          }}
        />
        <label htmlFor="pdf-upload" className="upload-button">
          <svg viewBox="0 0 24 24" width="24" height="24" fill="currentColor">
            <path d="M6 2C4.9 2 4 2.9 4 4V20C4 21.1 4.9 22 6 22H18C19.1 22 20 21.1 20 20V8L14 2H6ZM13 9V3.5L18.5 9H13Z" />
          </svg>
        </label>
      </div>

      <div
        ref={pdfContainerRef}
        className="pdf-viewer flex-1"
        onMouseUp={handleTextSelection}
      ></div>

      {/* 标注弹窗 */}
      {showAnnotationPopup && (
        <div
          ref={popupRef}
          className="annotation-popup"
          style={{
            position: "absolute",
            zIndex: 1000,
            backgroundColor: "white",
            border: "1px solid #ccc",
            borderRadius: "4px",
            padding: "10px",
            boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
          }}
        >
          <div
            className="selected-text-container"
            style={{ marginBottom: "10px", position: "relative" }}
          >
            <div
              className="selected-text"
              style={{ fontWeight: "bold", paddingRight: "30px" }}
            >
              {currentSelection.text}
            </div>
            <button
              onClick={() => {
                navigator.clipboard
                  .writeText(currentSelection.text)
                  .then(() => {
                    // 显示复制成功提示
                    const copyButton = document.querySelector(
                      ".copy-button"
                    ) as HTMLElement;
                    if (copyButton) {
                      const originalText = copyButton.innerHTML;
                      copyButton.innerHTML = "✓";
                      copyButton.style.backgroundColor = "#4CAF50";
                      alert("文本已复制到剪贴板！");
                      setTimeout(() => {
                        copyButton.innerHTML = originalText;
                        copyButton.style.backgroundColor = "#f1f1f1";
                      }, 1500);
                    }
                  })
                  .catch((err) => {
                    console.error("复制失败:", err);
                  });
              }}
              className="copy-button"
              style={{
                position: "absolute",
                top: "0",
                right: "0",
                padding: "2px 5px",
                backgroundColor: "#f1f1f1",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
                fontSize: "0.8em",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
              title="复制文字"
            >
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
              </svg>
            </button>
          </div>

          <div
            className="color-selector"
            style={{ display: "flex", marginBottom: "10px" }}
          >
            {["#FFEB3B", "#4CAF50", "#2196F3", "#F44336", "#9C27B0"].map(
              (color) => (
                <div
                  key={color}
                  onClick={() => setAnnotationColor(color)}
                  style={{
                    width: "20px",
                    height: "20px",
                    backgroundColor: color,
                    margin: "0 5px",
                    cursor: "pointer",
                    border:
                      color === annotationColor
                        ? "2px solid #000"
                        : "1px solid #ccc",
                    borderRadius: "50%",
                  }}
                />
              )
            )}
          </div>

          <textarea
            placeholder="添加备注..."
            value={annotationNote}
            onChange={(e) => setAnnotationNote(e.target.value)}
            style={{
              width: "100%",
              padding: "5px",
              marginBottom: "10px",
              borderRadius: "4px",
              border: "1px solid #ccc",
            }}
          />

          <div
            className="buttons"
            style={{ display: "flex", justifyContent: "flex-end" }}
          >
            <button
              onClick={cancelAnnotation}
              style={{
                marginRight: "10px",
                padding: "5px 10px",
                backgroundColor: "#f1f1f1",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
              }}
            >
              取消
            </button>
            <button
              onClick={createAnnotation}
              style={{
                padding: "5px 10px",
                backgroundColor: "#4CAF50",
                color: "white",
                border: "none",
                borderRadius: "4px",
                cursor: "pointer",
              }}
            >
              标注
            </button>
          </div>
        </div>
      )}

      {/* 标注列表 */}
      <div
        className="annotations-list"
        style={{
          position: "fixed",
          right: "20px",
          top: "20px",
          width: "250px",
          maxHeight: "80vh",
          overflowY: "auto",
          backgroundColor: "white",
          border: "1px solid #ccc",
          borderRadius: "4px",
          padding: "10px",
          boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
          display: annotations.length ? "block" : "none",
        }}
      >
        <h3
          style={{
            marginTop: 0,
            borderBottom: "1px solid #eee",
            paddingBottom: "5px",
          }}
        >
          标注列表
        </h3>
        {annotations.map((anno) => (
          <div
            key={anno.id}
            style={{
              marginBottom: "10px",
              padding: "8px",
              borderLeft: `4px solid ${anno.color}`,
              backgroundColor: "#f9f9f9",
            }}
          >
            <div style={{ fontWeight: "bold", marginBottom: "5px" }}>
              {anno.text}
            </div>
            {anno.note && (
              <div style={{ fontSize: "0.9em", color: "#666" }}>
                {anno.note}
              </div>
            )}
            <div style={{ textAlign: "right", marginTop: "5px" }}>
              <button
                onClick={() => deleteAnnotation(anno.id)}
                style={{
                  padding: "2px 5px",
                  backgroundColor: "#f44336",
                  color: "white",
                  border: "none",
                  borderRadius: "2px",
                  cursor: "pointer",
                  fontSize: "0.8em",
                }}
              >
                删除
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default PdfTest;
